const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

// 获取环境变量，支持启动脚本设置的配置
const getApiConfig = () => {
  const apiHost = process.env.REACT_APP_API_HOST || 'localhost';
  const apiPort = process.env.REACT_APP_API_PORT || '8000';
  const apiProtocol = process.env.REACT_APP_API_PROTOCOL || 'http';
  
  return {
    host: apiHost,
    port: apiPort,
    protocol: apiProtocol,
    url: `${apiProtocol}://${apiHost}:${apiPort}`
  };
};

const apiConfig = getApiConfig();
const isDevelopment = process.env.NODE_ENV !== 'production';

console.log('🔧 Webpack配置信息:');
console.log(`   模式: ${isDevelopment ? '开发' : '生产'}`);
console.log(`   API代理目标: ${apiConfig.url}`);

module.exports = {
  mode: isDevelopment ? 'development' : 'production',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: isDevelopment ? 'bundle.js' : 'bundle.[contenthash].js',
    clean: true,
    publicPath: '/',
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react'],
          },
        },
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource',
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html',
      title: 'Medical Image Viewer',
      minify: isDevelopment ? false : {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
      },
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
      'process.env.REACT_APP_API_HOST': JSON.stringify(apiConfig.host),
      'process.env.REACT_APP_API_PORT': JSON.stringify(apiConfig.port),
      'process.env.REACT_APP_API_PROTOCOL': JSON.stringify(apiConfig.protocol),
      'process.env.REACT_APP_API_URL': JSON.stringify(apiConfig.url),
    }),
  ],
  devServer: {
    static: {
      directory: path.join(__dirname, 'public'),
    },
    compress: true,
    port: parseInt(process.env.PORT) || 3000,
    host: process.env.HOST || 'localhost',
    hot: true,
    open: false, // 让启动脚本控制是否打开浏览器
    historyApiFallback: true,
    // 动态代理配置，支持启动脚本的后端配置
    proxy: {
      '/api': {
        target: apiConfig.url,
        changeOrigin: true,
        secure: false,
        logLevel: isDevelopment ? 'info' : 'silent',
        onProxyReq: (proxyReq, req, res) => {
          if (isDevelopment) {
            console.log(`🔄 代理请求: ${req.method} ${req.url} -> ${apiConfig.url}${req.url}`);
          }
        },
        onError: (err, req, res) => {
          console.error(`❌ 代理错误: ${err.message}`);
          console.error(`   目标地址: ${apiConfig.url}`);
          console.error(`   请确保后端服务正在运行`);
        }
      },
    },
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  // 开发模式优化
  ...(isDevelopment && {
    devtool: 'eval-source-map',
    optimization: {
      splitChunks: false,
    },
  }),
  // 生产模式优化
  ...(!isDevelopment && {
    devtool: 'source-map',
    optimization: {
      splitChunks: {
        chunks: 'all',
        cacheGroups: {
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors',
            chunks: 'all',
          },
        },
      },
      minimize: true,
    },
    performance: {
      maxAssetSize: 512000,
      maxEntrypointSize: 512000,
    },
  }),
}; 